import { OnInit, Component, OnDestroy } from '@angular/core'
import { Router } from '@angular/router'
import { I18NService } from '@core'
import { NzMessageService } from 'ng-zorro-antd'
import { of } from 'rxjs'
import { concatMap } from 'rxjs/operators'

import { ComWindow } from '@shared/classes/ComWindowClass'
import { PageService } from '@shared/services/page.service'
import { CurrencyService } from '@shared/services/currency.service'
import { INewPageColumn } from '@shared/interfaces/common'
import { numScale } from 'app/utils/helpers'
import { ManualAuthNewSystemComponent } from './pages/system.component'
import { ManualAuthNewFormComponent } from './pages/manual-auth-form.component'
import { ManualAuthService } from '../manual-auth.service'
import { ManualAuthDataService } from '../manual-auth-data.service'
import { IManualAuthCollection } from '@shared/interfaces/manualAuth'
import * as dayjs from 'dayjs'

@Component({
  selector: 'app-merchant-manual-auth-new',
  templateUrl: './new.component.html',
})
export class NewManualAuthComponent implements OnInit, OnDestroy {
  constructor(
    private manualAuthService: ManualAuthService,
    private dataService: ManualAuthDataService,
    private router: Router,
    private msgSrv: NzMessageService,
    private pageService: PageService,
    private i18n: I18NService,
    private currencyService: CurrencyService,
  ) {}

  pages: INewPageColumn[] = []

  ngOnInit() {
    this.pages = [
      {
        component: new ComWindow(ManualAuthNewSystemComponent, { title: 'GENERAL.INFO.OTHER.SYSTEM_INFO' }),
      },
      {
        component: new ComWindow(ManualAuthNewFormComponent, { title: 'OPERATION.MANUAL_AUTH.TITLE.MANUAL_AUTH_INFO' }),
      },
    ]
  }

  ngOnDestroy(): void {
    this.dataService.setManualAuthData({})
  }

  submit(data: IManualAuthCollection): void {
    of(data)
      .pipe(
        concatMap(formData => {
          return this.currencyService.getDecimalByCode(formData.currency).pipe(
            concatMap(digital => {
              formData.transAmt = numScale(formData.transAmt, digital)
              formData.effectiveDate = dayjs(formData.effectiveDate).format('YYMM')
              return this.manualAuthService.createManualAuth(formData)
            }),
          )
        }),
      )
      .subscribe(() => {
        this.dataService.setManualAuthData({})
        this.pageService.triggerGuardAlive(false)
        this.msgSrv.success(this.trans('GENERAL.NOTIFICATION.CREATE_SUCCESS'))
        this.router.navigateByUrl('/operations/authManual/list')
      })
  }

  private trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
